package com.xiaohao.springbootadmintemplate.filter;

import com.xiaohao.springbootadmintemplate.config.securitycontext.UserDetailsServiceImpl;
import com.xiaohao.springbootadmintemplate.util.JwtTokenUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SecurityContextAuthenticationFilter extends BasicAuthenticationFilter {
    private UserDetailsServiceImpl userDetailsService;
    public SecurityContextAuthenticationFilter(AuthenticationManager authenticationManager,UserDetailsServiceImpl userDetailsService) {
        super(authenticationManager);
        this.userDetailsService=userDetailsService;
    }

    @Override
    //验证token
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        //获取请求头中的Authorization字段，该字段的值就是Token
        String authHeader = request.getHeader("Authorization");
        //token的前缀，例如请求头Authorization：Bearer eyabcdefghi
        String tokenHead = "Bearer ";
        //如果没有该请求头则拦截返回
        if (authHeader == null || !authHeader.startsWith(tokenHead)) {
            chain.doFilter(request, response);
            return;
        }
        String authToken = authHeader.substring(tokenHead.length());
        //使用jwt验证请求头是否合法，并返回用户名
        String username = JwtTokenUtil.getUsername(authToken);
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        System.out.println(userDetails);
        //设置用户到Security的上下文中
        SecurityContextHolder.getContext().setAuthentication(
                new UsernamePasswordAuthenticationToken(username,
                        null, userDetails.getAuthorities()));
        chain.doFilter(request, response);
    }
}
